//
//  LBCourseCollectVC.m
//  V-Learn
//
//  Created by Apple on 2019/1/11.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "LBCourseCollectVC.h"
#import "LBSaomangCell.h"
#import "LBCoureseDetailVC.h"
#import "LBCollectCell.h"
#import "CourseDetailsViewController.h"
#import "LBCourseCollectModel.h"
@interface LBCourseCollectVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *coureseLists;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property(nonatomic, strong) NSMutableArray *deleteArr;//删除数据的数组
@property (nonatomic, strong) UIView *funcView;//底部全选 移除 视图
@property (nonatomic, strong) UIView * noDataView;//没有数据视图
@end

@implementation LBCourseCollectVC
{
    NSInteger  _page;
    NSInteger  _currentCount;
    NSInteger  _pageIndex;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)coureseLists{
    if (!_coureseLists) {
        _coureseLists = [NSMutableArray array];
    }
    return _coureseLists;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, LBNAVBAR_HEIGHT, ScreenW, ScreenH-LBNAVBAR_HEIGHT-44) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.editing = NO;
    }
    return _tableView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = [UIView new];

    
    self.deleteArr = [NSMutableArray array];
    
    [self setupUI];

    
    
    //下拉刷新
    [self downRefreshData];
}

#pragma mark - 设置界面
- (void)setupUI {
    self.navigationItem.title = @"收藏";
    self.view.backgroundColor = [UIColor whiteColor];

    UIButton *rightBtn = [[UIButton alloc] init];
    [rightBtn setTitle:@"管理" forState:UIControlStateNormal];
    [rightBtn setTitleColor:rgb(51, 51, 51) forState:UIControlStateNormal];
    rightBtn.titleLabel.font = LBFont(15*kScaleFit);
    rightBtn.frame = CGRectMake(0, 0, 35, 35);
    [rightBtn addTarget:self action:@selector(selectedBtn:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = item;
    
    
    UIView *funcView = [[UIView alloc] init];
    _funcView = funcView;
    funcView.hidden = YES;
    funcView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:funcView];
    [funcView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    
    UIButton * delBtn = [[UIButton alloc] init];
    [delBtn setTitle:@"删除" forState:UIControlStateNormal];
    delBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    delBtn.backgroundColor = rgb(233,84,18);
    [delBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [funcView addSubview:delBtn];
    [delBtn addTarget:self action:@selector(deleteClick:)
     forControlEvents:UIControlEventTouchUpInside];
    [delBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(49);
        make.right.mas_equalTo(0);
        
    }];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
}

- (void)downRefreshData{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadDownNewDataSecond];
    }];
    
    //2.上拉
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadUpNewDataSecond)];
    //在刷新数据覆盖不显示数据的 cell 的分割线,如果不设置,则会显示 cell 的分割线
    UIView *footView = [UIView new];
    self.tableView.tableFooterView = footView;
    if (@available(iOS 11.0, *)) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark -- 下拉刷新
-(void)loadDownNewDataSecond{
    //默认页数、条数
    _page = 1;
    _currentCount = 10;
    [self requestData:_currentCount page:_page];
}
#pragma mark -- 上拉加载
-(void)loadUpNewDataSecond{
    _page++;//页数
    _currentCount = 10;
    _pageIndex = _page*_currentCount;
    [self requestData:_pageIndex page:_pageIndex];
}
- (void)requestData:(NSInteger)currentCount page:(NSInteger)page{
    NSLog(@"%@",WKCourseList_WKURL);
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    NSString *token = [UserModel getUserModel].token;
    [data setObject:token forKey:@"token"];
    [data setObject:@(page) forKey:@"page"];
    [data setObject:@(currentCount) forKey:@"num"];
    [WYHXNetWorkManager get:WKMyCollectCourse_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
        NSString *code = responseObj[@"code"];
        if ([code integerValue]==200) {
            
            if (page==1&&self.coureseLists.count>0) {
                [self.coureseLists removeAllObjects];
                [self.tableView reloadData];
            }
            NSArray *arr = [LBCourseCollectModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
            [self.coureseLists addObjectsFromArray:arr];
            
//            for (LBCourseCollectModel *model in arr) {
//
//                [self.dataArray addObject:model.courseOutputDTO];
//            }
//            for (int i=0; i<arr.count; i++) {
//                LBCourseCollectModel *model = arr[i];
//                if ([model.collectType isEqualToString:@"2"]) {
//                    [self.dataArray addObject:model.packageOutputDTO];
//                }else{
//                    [self.dataArray addObject:model.courseOutputDTO];
//                }
//
//            }
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
        
    }];
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleNone;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.coureseLists.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier=@"timewsitch";
    LBCollectCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[LBCollectCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    LBCourseCollectModel *model = self.coureseLists[indexPath.section];
    cell.model = model;
    return cell;
    
}
//选择按钮点击响应事件
- (void)selectedBtn:(UIButton *)button {
    
    //支持同时选中多行
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    self.tableView.editing = !self.tableView.editing;
    [self.deleteArr removeAllObjects];
    if (self.tableView.editing) {
        self.tableView.mj_header = nil;
        self.tableView.mj_footer = nil;
        
        self.navigationItem.rightBarButtonItem.title = @"取消";
        _funcView.hidden = NO;
        
    }else{
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self loadDownNewDataSecond];
        }];
        
        //2.上拉
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadUpNewDataSecond)];
        self.navigationItem.rightBarButtonItem.title = @"管理";
        _funcView.hidden = YES;
    }
    
}
//删除按钮点击事件
- (void)deleteClick:(UIButton *) button {
    
    if (self.tableView.editing) {
        if (!self.deleteArr.count) {
            [SVProgressHUD showErrorWithStatus:@"请先选择课程"];
            [SVProgressHUD dismissWithDelay:1.0f];
            return;
        }
        //删除
        NSMutableArray *deleteIds = @[].mutableCopy;
        for (LBCourseCollectModel *model in self.deleteArr) {
            [deleteIds addObject:model.collectId];
        }
        NSString *flags = [deleteIds componentsJoinedByString:@","];
        
        //    NSString *str = consultPro.professions;
        //    NSArray *arr = [str componentsSeparatedByString:@","];
        
        NSMutableDictionary *data = [NSMutableDictionary dictionary];
        
        NSString *token = [UserModel getUserModel].token;
        
        [data setObject:token forKey:@"token"];
        [data setObject:flags forKey:@"collectIds"];
//        [SVProgressHUD show];
        [WYHXNetWorkManager post:WKCancelCollectCourse_WKURL params:data completionHandler:^(id responseObj, NSError *error) {
//            [SVProgressHUD dismiss];
            NSString *code = responseObj[@"code"];
            NSString *msg = responseObj[@"msg"];
            if ([code integerValue]==200) {
                NSLog(@"%@",responseObj);
                //                [self loadDownNewDataSecond];
                [MBProgressHUD showSuccess:msg toView:self.view];
                [self.coureseLists removeObjectsInArray:self.deleteArr];
                [self selectedBtn:nil];
                [self.tableView reloadData];
            }
        }];
        if (self.deleteArr.count == 0) {
            self.navigationItem.rightBarButtonItem.title = @"管理";
            _funcView.hidden = YES;
        }
        
    }
    else return;
}
//是否可以编辑  默认的时YES
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//选择编辑的方式,按照选择的方式对表进行处理
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
    }
    
}

//选中时将选中行的在self.dataArray 中的数据添加到删除数组self.deleteArr中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        LBCourseCollectModel *consultPro = self.coureseLists[indexPath.section];
        if (![self.deleteArr containsObject:consultPro]) {
            [self.deleteArr addObject:consultPro];
        }
    }else {
        LBCourseCollectModel *model = self.coureseLists[indexPath.section];
        
        if ([model.collectType isEqualToString:@"1"]) {//课程
            LBCoureseDetailVC *detailVC = [LBCoureseDetailVC new];
            detailVC.courseId = model.courseId;
            detailVC.type = model.collectType;
//            detailVC.courseInfo = model.courseOutputDTO.courseInfo;
            [self.navigationController pushViewController:detailVC animated:YES];
        }else{                                         //2 课程包
            CourseDetailsViewController *packVC = [[CourseDetailsViewController alloc] initWithNibName:@"CourseDetailsViewController" bundle:nil];
            packVC.packId = model.courseId;
            packVC.collectType = model.collectType;
            packVC.courseInfo = model.packageOutputDTO.packageInfo;
            [self.navigationController pushViewController:packVC animated:YES];
        }
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}
//取消选中时 将存放在self.deleteArr中的数据移除
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath  {
    if (tableView.editing) {
        LBCourseCollectModel *consultPro = self.coureseLists[indexPath.section];
        if ([self.deleteArr containsObject:consultPro]) {
            [self.deleteArr removeObject:consultPro];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

@end
